<template>
	<view class="content">
		<view class="text-right">
			<button v-for="(v,k) in sorts" :key="k" class="small" :class="{active:sort==k}" @tap="sortBy(k)">{{v}}{{sort==k?desc>0?'升':'降':''}}</button>
			<button type="primary" class="small" @tap="add">添加</button>
		</view>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll">
			<view v-for="item in sortList" :key="item.objectId">
				<view>
					<text class="mr-2">{{item.price>0?'收':'送'}} <text class="blue--text">{{item.name}}</text> </text>
					<text class="mr-2" v-if="item.price>0"> <text class="green--text">{{item.price}}</text> 元</text>
					<text class="mr-2" v-else> <text class="red--text">{{-item.price}}</text> 元</text>
					<text v-if="item.agent"><text class="small">by</text><text class="blue--text">{{item.agent}}</text></text>
				</view>
				<view class="nowrap text-right small">{{item.createdAt}} <text class="red--text ml-1" @click="del(item)">删除</text></view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import * as platform from '../common/platfrom'
import { mapState } from 'vuex'
import Bmob from 'hydrogen-js-sdk'

export default {
	data() {
		return {
			list: [],
			sorts: {
				createAt: '时间',
			},
			sort: 'createAt',
			desc: -1,
		}
	},
	computed: {
		...mapState(['hasLogin']),
		sortList() {
			if (!this.sort) return this.list;
			let list = this.list.concat()
			list.sort((a, b) => (a[this.sort] >= b[this.sort] ? -1 : 1) * this.desc)
			return list;
		}
	},
	methods: {
		upper(e) {
			console.log(e)
		},
		lower(e) {
			console.log(e)
		},
		scroll(e) {
			console.log(e)
		},
		add(e) {
			uni.navigateTo({ url: '/pages/form/addRecord' })
		},
		sortBy(k) {
			if (this.sort != k) {
				this.sort = k;
				this.desc = 1;
			} else if (this.desc > 0)
				this.desc = -1
			else
				this.sort = '';
		},
		del(item) {
			uni.showModal({
				title: '是否删除',
				success: async () => {
					const query = Bmob.Query('record');
					await query.destroy(item.objectId)
					let idx = this.list.indexOf(item)
					this.list.splice(idx, 1)
					this.$toast.success('删除成功')
				}
			})
		}
	},
	onLoad() {
		if (!this.hasLogin) {
			platform.goToLogin()
		}
	},
	onShow() {
		var query = Bmob.Query('record')
		query.find().then((data) => {
			this.list = data;
			console.log(data)
		})
	}
}
</script>